import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../core/utils/show_toast.dart';
import '../../../../data/controllers/player_controller.dart';
import '../../../../data/models/auth/user.dart';

part 'all_players_state.dart';

class PlayersTabCubit extends Cubit<PlayersTabState> {
  PlayersTabCubit() : super(PlayersTabInitial());

  static PlayersTabCubit get(context) => BlocProvider.of(context);

  TextEditingController searchBox = TextEditingController();

  List<User> allUsers = [];
  List<User> users = [];


  bool searchFlag = false;

  void init() {
    getAllUsers();
  }

  Future getAllUsers()async{
    searchBox.clear();
    emit(PlayersTabLoading());
    await PlayerController.getAllPlayers().catchError((e){
      emit(PlayersTabError());
      return null;
    }).then((value){
      if(value != null && value.state) {
        users = List<User>.generate(value.data.length, (index) => User.fromJson(value.data[index]));
        allUsers = users;
        emit(PlayersTabDone());
      }else if(value != null){
        showMessage(value.message);
        emit(PlayersTabError());
      }else{
        if (kDebugMode) {
          print('value is null');
        }
      }
    });
  }

  onSearchTap(){
    print(searchFlag);
    searchFlag = !searchFlag;
    emit(PlayersTabUpdate());
  }
  onSearch(String text){
    if(text.isEmpty){
      users = allUsers;
    }else {
      users = allUsers.where(
            (element) =>
                element.fullName.contains(text) ||
                    element.username?.contains(text)==true,

      ).toList();
    }
    emit(PlayersTabUpdate());
  }

}
